//
//  CLSubViewController.m
//  chanlin
//
//  Created by Ryan on 14-12-21.
//  Copyright (c) 2014年 chanlin. All rights reserved.
//

#import "CLSubViewController.h"
#import "CLTopic.h"
#import "IFCoreDataManager.h"
#import "IFIndexCell.h"
#import "IFIndexFocusCell.h"
#import "IFIndexIconCell.h"
#import "IFIndexSlidesCell.h"
#import "CLTopicImgCell.h"
#import "CLTopicModel.h"
#import "CLTopicTextCell.h"
#import "CLPushAnimatedRight.h"
#import "CLSlidersViewController.h"
#import "CLDocViewController.h"
#import "CLVideoViewController.h"
#import "CLTopicViewController.h"
#import "UIImageView+WebCache.h"

@interface CLSubViewController ()

@property (nonatomic,strong)UIImageView *headView;
@property (nonatomic,strong)UILabel *titleLabel;
@property (nonatomic,unsafe_unretained) int pageNum;

@end

@implementation CLSubViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    self.tableView.frame=CGRectMake(0, 82.f, GlobleWidth, GlobleHeight-82.f-44);
    
    
    self.headView=[[UIImageView alloc] init];
    self.headView.frame=CGRectMake(0, 20, GlobleWidth, 62.f);
    [self.view addSubview:self.headView];
    
//    UILabel *title=[[UILabel alloc] init];
//    title.font=[UIFont systemFontOfSize:20];
//    title.frame=CGRectMake((GlobleWidth-300.f)/2.f, 40.f, 300.f, title.font.lineHeight);
//    title.textColor=RGB(98, 101, 113);
//    title.textAlignment=NSTextAlignmentCenter;
//    title.text=self.title;
//    self.titleLabel=title;
//    [self.headView addSubview:title];
    

    
    self.icon=[[UIImageView alloc] init];
    self.icon.frame=CGRectMake(11.f, 12.f, 35.f, 35.f);
    [self.headView addSubview:self.icon];
    
    self.titlelabelc=[[UILabel alloc] init];
    self.titlelabelc.font=[UIFont systemFontOfSize:16.f];
    self.titlelabelc.textColor=RGB(0x3e, 0x3e, 0x3e);
    self.titlelabelc.frame=CGRectMake(self.icon.right+13.f, self.icon.top+2, GlobleWidth-(self.icon.right+13.f), self.titlelabelc.font.lineHeight);
    [self.headView addSubview:self.titlelabelc];
    
    self.info=[[UILabel alloc] init];
    self.info.font=[UIFont systemFontOfSize:10.f];
    self.info.textColor=RGB(0x58, 0x57, 0x57);
    self.info.frame=CGRectMake(self.titlelabelc.left, self.titlelabelc.bottom + 6, self.titlelabelc.width, 10);
    [self.headView addSubview:self.info];
    if(self.objectiveId){
    CLList *list=(CLList *)[CLList managerObjWithObjectID:self.objectiveId];
        [self loadData:list];
    }else{
        [self loadDic:self.dic];
    }
    
    
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"sort" ascending:YES];
    NSFetchRequest *req = [[NSFetchRequest alloc] initWithEntityName:@"CLTopic"];
    req.predicate = [NSPredicate predicateWithFormat:@"topicId=%@", [NSString stringWithFormat:@"sub%@",self.itemId]];
    req.sortDescriptors = @[sort];
    self.fetch = [[NSFetchedResultsController alloc] initWithFetchRequest:req
                                                     managedObjectContext:[IFCoreDataManager sharedInstance].mainMoc
                                                       sectionNameKeyPath:nil
                                                                cacheName:nil];
    self.fetch.delegate=self;
    [self.fetch performFetch:nil];
    
    if([self isViewLoaded])
        [self reloadTable];


    
    
    
    [self.tableView becameHeadReflashLoading];
    
    self.tool=[self showToolbarWithType:0];
    
    [MobClick event:@"page"
         attributes:@{@"pageId":[@"sub_" stringByAppendingString:_safeStr(self.itemId)],
                      @"title":_safeStr([self.dic sgrGetStringForKey:@"title"])}];

    
}

- (void)loadData:(CLList *)newsList{
    if(_isStrNotNull(newsList.thumnail)){
        [self.icon sd_setImageWithURL:[NSURL URLWithString:newsList.thumnail] placeholderImage:nil];
    }else{
        self.icon.image=nil;
    }
    
    self.titlelabelc.text=newsList.title;
    self.info.text=newsList.info;
}

- (void)loadDic:(NSDictionary *)dic{
    if(_isStrNotNull([dic sgrGetStringForKey:@"titlepic"])){
        [self.icon sd_setImageWithURL:[NSURL URLWithString:[dic sgrGetStringForKey:@"titlepic"]] placeholderImage:nil];
    }else{
        self.icon.image=nil;
    }
    
    self.titlelabelc.text=[dic sgrGetStringForKey:@"title"];
    self.info.text=[dic sgrGetStringForKey:@"smalltext"];
}

- (void)setItemId:(NSString *)itemId{
    [self setOnlyItemId:itemId];
}


- (void)loadImg:(NSString *)url{
    if(_isStrNULL(url))return;
    [self.headView  sd_setImageWithURL:[NSURL URLWithString:url]
                      placeholderImage:nil
                             completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                                 if(error==nil &&image){
                                     self.titleLabel.hidden=YES;
                                 }else{
                                     self.titleLabel.hidden=NO;
                                 }
                             }];
}

-(void)jTableViewStartHeadLoading:(JTableView *)tableView{
    self.pageNum=1;
    __weak typeof(self) me=self;
    if([@"1" isEqualToString:[self.channel sgrGetStringForKey:@"tpl"]] ){
        
        
        
        [[CLTopicModel sharedInstance] getListWithClassId:self.itemId
                                                     page:self.pageNum
                                                lastTopic:nil
                                                  uiBlock:^(BOOL success, id responseObj, NSString *message) {
                                                      if(success){
                                                          [me loadImg:[responseObj sgrGetStringForKey:@"headImg"]];
                                                          [me.tableView stopHeadLoading];
                                                          
                                                      }else{
                                                          [[CLGloble sharedInstance] showTieAlertMessage:@"加载失败"
                                                                                              subMessage:message];
                                                      }
                                                  }];

        
        
        
        
        
    }else if([@"-1" isEqualToString:[self.channel sgrGetStringForKey:@"tpl"]] ){
        [[CLTopicModel sharedInstance] getBlistWithClassId:self.itemId
                                                      page:self.pageNum
                                                 lastTopic:nil
                                                   uiBlock:^(BOOL success, id responseObj, NSString *message) {
                                                       if(success){
                                                           [me loadImg:[responseObj sgrGetStringForKey:@"headImg"]];
                                                           [me.tableView stopHeadLoading];
                                                           
                                                       }else{
                                                           [[CLGloble sharedInstance] showTieAlertMessage:@"加载失败"
                                                                                               subMessage:message];
                                                       }
                                                       
                                                   }];
    
    }else{
    
        [[CLTopicModel sharedInstance] getWlistWithClassId:self.itemId
                                                      page:self.pageNum
                                                 lastTopic:nil
                                                   uiBlock:^(BOOL success, id responseObj, NSString *message) {
                                                       if(success){
                                                           [me loadImg:[responseObj sgrGetStringForKey:@"headImg"]];
                                                           [me.tableView stopHeadLoading];
                                                           
                                                       }else{
                                                           [[CLGloble sharedInstance] showTieAlertMessage:@"加载失败"
                                                                                               subMessage:message];
                                                       }
                                                       
                                                   }];
        
    }
    
    

}

- (void)jTableViewStartBottomMoreLoading:(JTableView *)tableView{
    __weak typeof(self) me=self;
    
    if([@"1" isEqualToString:[self.channel sgrGetStringForKey:@"tpl"]]){
        
        
        
        [[CLTopicModel sharedInstance] getListWithClassId:self.itemId
                                                     page:self.pageNum+1
                                                lastTopic:self.fetch.fetchedObjects.lastObject
                                                  uiBlock:^(BOOL success, id responseObj, NSString *message) {
                                                      if(success){
                                                          
                                                          [me.tableView stopBottomMoreWithScuessLoading];
                                                          me.pageNum++;
                                                      }else{
                                                          [me.tableView stopBottomMoreWithNothingLoading];
                                                      }
                                                  }];
        
        
       

    }else if([@"-1" isEqualToString:[self.channel sgrGetStringForKey:@"tpl"]] ){
    
        [[CLTopicModel sharedInstance] getBlistWithClassId:self.itemId
                                                     page:self.pageNum+1
                                                lastTopic:self.fetch.fetchedObjects.lastObject
                                                  uiBlock:^(BOOL success, id responseObj, NSString *message) {
                                                      if(success){
                                                          
                                                          [me.tableView stopBottomMoreWithScuessLoading];
                                                          me.pageNum++;
                                                      }else{
                                                          [me.tableView stopBottomMoreWithNothingLoading];
                                                      }
                                                  }];
    
    }else{
    
    
        [[CLTopicModel sharedInstance] getWlistWithClassId:self.itemId
                                                      page:self.pageNum+1
                                                 lastTopic:nil
                                                   uiBlock:^(BOOL success, id responseObj, NSString *message) {
                                                       if(success){
                                                           me.pageNum++;
                                                           [me.tableView stopBottomMoreWithScuessLoading];
                                                       }else{
                                                           [me.tableView stopBottomMoreWithNothingLoading];
                                                       }
                                                       
                                                   }];
    }
    
//    [[CLIndexModel sharedInstance] getListWithCategroy:[self.categroyDic sgrGetStringForKey:@"channelId"]
//                                              withPage:self.pageNum+1
//                                              lastList:self.fetch.fetchedObjects.lastObject
//                                               uiBlock:^(BOOL success, id responseObj, NSString *message) {
//                                                   if(success){
//                                                       me.pageNum++;
//                                                       [me.tableView stopBottomMoreWithScuessLoading];
//                                                   }else{
//                                                       [me.tableView stopBottomMoreWithFailedLoading];
//                                                   }
//                                               }];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CLTopic *newsList=[self.fetch objectAtIndexPath:indexPath];
    return newsList.cHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CLTopic *list=[self.fetch objectAtIndexPath:indexPath];
    IFIndexCell *cell=[self cellForStyle:list.style tableView:tableView];
    [cell loadTopicData:list];
    [cell setPlayVideo:list.link==CLList_video];
    return cell;
}


- (IFIndexCell *)cellForStyle:(int)style tableView:(UITableView *)tableView{
    if(style==CLList_style_focus){
        static NSString *cellID=@"IFIndexFocusCell";
        IFIndexIconCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if(!cell){
            cell=[[IFIndexIconCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        return cell;
    }else if (style==CLList_style_doc_img){
        static NSString *cellID=@"IFIndexIconCell";
        IFIndexIconCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if(!cell){
            cell=[[IFIndexIconCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        return cell;
    }else if(style==CLList_style_doc){
        static NSString *cellID=@"IFIndexTitleCell";
        IFIndexTitleCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if(!cell){
            cell=[[IFIndexTitleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        return cell;
    }else if(style==CLList_style_slide){
        static NSString *cellID=@"IFIndexSlidesCell";
        IFIndexSlidesCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if(!cell){
            cell=[[IFIndexSlidesCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        return cell;
    }else if(style==CLList_style_topic_img){
        static NSString *cellID=@"CLTopicImgCell";
        CLTopicImgCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if(!cell){
            cell=[[CLTopicImgCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        return cell;
    }else if(style==CLList_style_topic_text){
        static NSString *cellID=@"CLTopicImgCell";
        CLTopicTextCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if(!cell){
            cell=[[CLTopicTextCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        return cell;
    }
    
    return [[IFIndexCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"IFIndexCell"];
}

- (BOOL)showPopAction{
    return YES;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CLList *list=[self.fetch objectAtIndexPath:indexPath];
    [self clickOnList:list];
}

- (void)clickOnList:(CLList *)list{
    if(list.link==CLList_sliders){
        CLSlidersViewController *slider=[CLSlidersViewController new];
        slider.itemId=list.itemId;
        [[CLPushAnimatedRight sharedInstance] pushController:slider];
        
    }else if(list.link==CLList_doc){
        CLDocViewController *doc=[CLDocViewController new];
        doc.itemId=list.itemId;
        [[CLPushAnimatedRight sharedInstance] pushController:doc];
    }else if(list.link==CLList_topic){
        CLTopicViewController *topic=[CLTopicViewController new];
        topic.itemId=list.itemId;
        [[CLPushAnimatedRight sharedInstance] pushController:topic];
    }else if(list.link==CLList_video){
        CLVideoViewController *video=[CLVideoViewController new];
        video.itemId=list.itemId;
        [[CLPushAnimatedRight sharedInstance] pushController:video];
    }else if(list.link==CLList_audio){
        CLDocViewController *doc=[CLDocViewController new];
        doc.isAudio=YES;
        doc.itemId=list.itemId;
        [[CLPushAnimatedRight sharedInstance] pushController:doc];
    }
    
}





@end
